﻿using System.Collections.Generic;
using System.IO;

namespace Domain.Models
{
    public class SubjectsHandler
    {
        private const string MilitaryExtension = ".military";
        private readonly Dictionary<long, string> idPathDictionary;
        private readonly string subjectDirectoryPath = Directory.GetCurrentDirectory() + @"\Subjects\";
        private readonly IRepository<Subject> subjectRepository;

        public SubjectsHandler(IRepository<Subject> subjectRepository)
        {
            this.subjectRepository = subjectRepository;
            idPathDictionary = new Dictionary<long, string>();
        }

        public List<Subject> LoadAllSubjects()
        {
            var subjects = new List<Subject>();
            idPathDictionary.Clear();

            if (Directory.Exists(subjectDirectoryPath) == false)
                return subjects;

            var fileNames = Directory.GetFiles(subjectDirectoryPath);
            foreach (var fileName in fileNames)
            {
                if (new FileInfo(fileName).Extension != MilitaryExtension)
                    continue;

                var subject = subjectRepository.Load(fileName);

                if (subject == null)
                    continue;

                subjects.Add(subject);
                idPathDictionary.Add(subject.Id, fileName);
            }

            return subjects;
        }


        public void Save(Subject subject)
        {
            if (Directory.Exists(subjectDirectoryPath) == false)
                Directory.CreateDirectory(subjectDirectoryPath);

            if (idPathDictionary.ContainsKey(subject.Id))
                subjectRepository.Save(subject, idPathDictionary[subject.Id]);

            else
            {
                var fileName = subjectDirectoryPath + subject.Id.ToString() + MilitaryExtension;
                idPathDictionary.Add(subject.Id, fileName);
                subjectRepository.Save(subject, fileName);
            }
        }

        public Subject GetSubjectByName(string subjectName, List<Subject> subjects )
        {
            var subjectId = (int)GetSubjectIdByName(subjectName, subjects);
            return subjects.Find(x => x.Id == subjectId);
        }

        public long GetSubjectIdByName(string subjectName, List<Subject> subjects)
        {
            return subjects.Find(x => x.Name == subjectName).Id;
        }

        public void DeleteSubject(Subject subjectToDelete)
        {
            if (idPathDictionary.ContainsKey(subjectToDelete.Id))
                File.Delete(idPathDictionary[subjectToDelete.Id]);
        }
    }
}